package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.nest.WorkNest.R;
import com.nest.WorkNest.api.Api;
import com.nest.WorkNest.config.UserInfo;
import com.nest.WorkNest.tools.PhoneHelper;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

//注册
public class RegisterAct extends BaseActivity implements OnClickListener {
    private EditText et_telphone, et_authCode, et_pwd, et_pwd2, et_advisor;
    private CheckBox chk_read;
    private Button btn_register, btn_getcode;
    private TextView tv_register_xieyi;
    private String telphone, code, pwd, pwd2, usertype, advisor;
    private Context context = RegisterAct.this;
    private RadioButton rdoBtn_register_buyers, rdoBtn_register_designer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_register);
        initBar();
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("注册");
        ll_iv_actionbar_side_left.setVisibility(View.VISIBLE);
        back();
        initView();
    }

    public void initView() {
        et_telphone = (EditText) findViewById(R.id.edtTxt_registeract_telphone);
        et_authCode = (EditText) findViewById(R.id.edtTxt_registeract_identifyingcode);
        et_pwd = (EditText) findViewById(R.id.edtTxt_registeract_password);
        et_pwd2 = (EditText) findViewById(R.id.edtTxt_registeract_password2);
        chk_read = (CheckBox) findViewById(R.id.chk_registeract_read);
        btn_getcode = (Button) findViewById(R.id.btn_registeract_getcode);
        btn_register = (Button) findViewById(R.id.btn_registeract_register);
        rdoBtn_register_buyers = (RadioButton) findViewById(R.id.rdoBtn_register_buyers);
        rdoBtn_register_designer = (RadioButton) findViewById(R.id.rdoBtn_register_designer);
        et_advisor = (EditText) findViewById(R.id.edtTxt_registeract_advisor);
        tv_register_xieyi = (TextView) findViewById(R.id.tv_register_xieyi);
        btn_getcode.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        tv_register_xieyi.setOnClickListener(this);
        tv_register_xieyi.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 获取验证码
            case R.id.btn_registeract_getcode:
                telphone = et_telphone.getText().toString().trim();
                if (TextUtils.isEmpty(telphone)) {
                    showToast("手机号不能为空");
                } else if (!Utils.ismobiles(telphone)) {
                    showToast("请输入正确手机号");
                } else {
                    getAuthCode();
                    et_authCode.setFocusable(true);
                    et_authCode.setFocusableInTouchMode(true);
                    et_authCode.requestFocus();
                    new CountDownTimer(60000, 1000) {
                        // 第一个参数是总的倒计时时间
                        // 第二个参数是每隔多少时间(ms)调用一次onTick()方法
                        public void onTick(long millisUntilFinished) {
                            btn_getcode.setText("验证码(" + millisUntilFinished / 1000 + ")");
                            btn_getcode.setEnabled(false);
                            btn_getcode.setTextColor(Color.GRAY);
                        }

                        public void onFinish() {
                            btn_getcode.setText("获取验证码");
                            btn_getcode.setEnabled(true);
                            btn_getcode.setTextColor(Color.BLACK);
                        }
                    }.start();
                }

                break;
            // 注册
            case R.id.btn_registeract_register:
                initRegister();
                break;
            case R.id.tv_register_xieyi:
                startActivity(new Intent(context, ProtocolAct.class));
                break;
        }
    }

    public void initRegister() {
        telphone = et_telphone.getText().toString().trim();
        code = et_authCode.getText().toString().trim();
        pwd = et_pwd.getText().toString().trim();
        pwd2 = et_pwd2.getText().toString().trim();
        advisor = et_advisor.getText().toString().trim();
        if (rdoBtn_register_buyers.isChecked()) {
            usertype = "1";
        } else if (rdoBtn_register_designer.isChecked()) {
            usertype = "2";
        }
        if (TextUtils.isEmpty(telphone)) {
            showToast("手机号不能为空");
        } else if (TextUtils.isEmpty(code)) {
            showToast("请输入验证码");
        } else if (TextUtils.isEmpty(pwd)) {
            showToast("请输入密码");
        } else if (TextUtils.isEmpty(pwd2)) {
            showToast("请确认密码");
        } else if (!Utils.ismobiles(telphone)) {
            showToast("请输入正确手机号");
        } else if (Utils.ismobiles(telphone)) {
            if (!chk_read.isChecked()) {
                showToast("请阅读协议并勾选");
            } else if (chk_read.isChecked()) {
                if (!pwd.equals(pwd2)) {
                    showToast("两次密码输入不一致");
                    et_pwd2.setText("");
                } else if (pwd.equals(pwd2)) {
                    loadingRegister();
                }
            }
        }
    }

    private void loadingRegister() {
        JSONObject json = new JSONObject();
        RequestParams params = new RequestParams();
        params.setContentType(APPLICATION_WWW);
        try {
            json.put("systemId", Api.systemId);
            json.put("userName", telphone);
            json.put("password", pwd);
            json.put("authCode", code);
            json.put("userType", usertype);
            if (!TextUtils.isEmpty(advisor)) {
                json.put("advisor", advisor);
            }
            json.put("deviceId", PhoneHelper.OS());
            params.addBodyParameter("data", json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Api.register, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                LogUtils.d(arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtils.d("-------------------" + responseInfo.result);
                JSONObject jsonObject = Tool.getJsonObject(responseInfo.result);
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    String token = Tool.getString(jsonObject, "token");
                    fileHelper.putShareProf("", "");
                    fileHelper.putInt(UserInfo.USER_ID, 1);
                    fileHelper.putString(UserInfo.TEL_PHONE, telphone);
                    fileHelper.putString(UserInfo.PASSWORD, pwd);
                    fileHelper.putString(UserInfo.TOKEN, token);
                    fileHelper.putBoolean(UserInfo.USERINFO_ISLOGIN, true);
                    showToast("注册成功");
                    Intent intent = new Intent(context, MainTabAct.class);
                    startActivity(intent);
                } else if (Tool.getString(jsonObject, "resultCode").equals("9003")) {
                    showToast("该手机号已注册");
                } else if (Tool.getString(jsonObject, "resultCode").equals("9005")) {
                    showToast("验证码错误");
                } else {
                    showToast("注册失败");
                }

            }

        });
    }

    private void getAuthCode() {
        JSONObject json = new JSONObject();
        RequestParams params = new RequestParams();
        params.setContentType(APPLICATION_WWW);
        try {
            json.put("systemId", Api.systemId);
            json.put("userName", telphone);
            json.put("codeType", "1");
            json.put("userNameType", "1");
            params.addBodyParameter("data", json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Api.getAuthCode, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        LogUtils.d("==failed=======" + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {

                        JSONObject jsonObject = Tool.getJsonObject(responseInfo.result);
                        if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                            fileHelper.putShareProf("", "");
                            showToast("获取成功");
                        } else {
                            showToast(Tool.getString(jsonObject, "MSG"));
                        }
                    }
                });

    }


    public boolean onTouchEvent(MotionEvent event) {
        try {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                    manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.onTouchEvent(event);
    }
}
